﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Daco
{
    public class TreeNodeCollection : CollectionBase
    {
        public virtual ITreeNode this[int index]
        {
            get
            {
                return (ITreeNode)List[index];
            }
        }

        public virtual ITreeNode this[string nodeName]
        {
            get
            {
                return GetNodeByName(nodeName);
            }
            set
            {
                for (int i = 0; i < List.Count; i++)
                {
                    if (string.Compare(nodeName, this[i].Name, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        List[i] = value;
                    }
                }
            }
        }

        public void AddNode(ITreeNode node)
        {
            List.Add(node);
        }

        public new void RemoveAt(int index)
        {
            List.RemoveAt(index);
        }

        public void Remove(ITreeNode node)
        {
            List.Remove(node);
        }

        public void Insert(int index, ITreeNode node)
        {
            if (index > -1 && index < List.Count)
                List.Insert(index, node);
        }

        protected override void OnInsert(int index, object value)
        {
            ITreeNode newNode = (ITreeNode)value;

            foreach (ITreeNode node in List)
            {
                if (string.Compare(newNode.Name, node.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    throw new DuplicateWaitObjectException();
                }
            }

            base.OnInsert(index, value);
        }
        
        private ITreeNode GetNodeByName(string nodeName)
        {
            foreach (ITreeNode node in List)
            {
                if (string.Compare(node.Name, nodeName, StringComparison.CurrentCultureIgnoreCase) == 0)
                    return node;
            }
            return null;
        }
    }

    public interface ITreeNode
    {
        string Name { get; set; }
        string Value { get; set; }
        bool HasNodes { get; }
        bool Selected { get; set; }
        ITreeNode Parent { get; }
        TreeNodeCollection Nodes { get; }
    }

    public interface ITree
    {
        TreeNodeCollection Nodes { get; }
        ITreeNode SelectedNode { get; }
    }
}
